package edu.ptu.zhiyan.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.DeleteById;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.ptu.zhiyan.entity.User;
import edu.ptu.zhiyan.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 使用注意：
 *  UserService：此类继承ServiceImpl类【泛型】，从而可以实现，通过UserMapper操作数据库，返回结果为User
 *               实现IService<User>接口
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IService<User> {

    @Resource
    UserMapper userMapper;

    // 添加用户
    public User saveUser(User user){
        try {
            userMapper.insert(user);    // 这个插入操作不需要程序员写。直接调用即可
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            User res = userMapper.selectOne(
                    queryWrapper.eq(User.USERNAME,user.getUsername())
                            .eq(User.PASSWORD,user.getPassword())
            );
            return res;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
    // 查询用户
    public User queryUser(Integer uid){
        try {
            // QueryWrapper: 查询包装器
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            User res = userMapper.selectOne(queryWrapper.eq(User.UID,uid)); // 返回的是查找到的一整行数据
            //System.out.println("User:" + res);
            return res;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    public User loginUser(User user){
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            User res = userMapper.selectOne(
                    queryWrapper.eq(User.USERNAME,user.getUsername())
                            .eq(User.PASSWORD,user.getPassword())
            );
            return res;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    public boolean removeUser(Integer id){
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(User.UID,id) ;
            int delete = userMapper.delete(queryWrapper);
            //delete = userMapper.delete(queryWrapper) ;
            System.out.println("delete return count = " + delete);
            return true ;
        } catch (Exception e) {
            e.printStackTrace();
            return false ;
        }
    }
}